//
//  EmoticonViewController.swift
//  表情键盘
//
//  Created by 陈恒均 on 2018/2/23.
//  Copyright © 2018年 陈恒均. All rights reserved.
//

import UIKit
private let EmoticonCell = "EmoticonCell"
class EmoticonViewController: UIViewController {

    // MARK:- 定义属性
    var emoticonCallBack : (_ emoticon : Emoticon) -> ()
    
    
    
    // MARK:- 懒加载属性
    
    private lazy var conllecitonView : UICollectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: EmoticonCollectionViewLayout())
    
    private lazy var toolBar : UIToolbar = UIToolbar()
    
    private lazy var manager = EmoticonManger()
    
    
    // MARK:- 自定义构造函数
    init(emoticonCallBack : @escaping (_ emoticon : Emoticon) -> ()) {
        self.emoticonCallBack = emoticonCallBack
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
        
        conllecitonView.backgroundColor = UIColor.lightGray
  
    }

}

// MARK:- 设置界面UI

extension EmoticonViewController{

     private func setupUI(){
        view.addSubview(conllecitonView)
        view.addSubview(toolBar)
        
        
        // MARK:- 使用VFL布置控件
        conllecitonView.translatesAutoresizingMaskIntoConstraints = false
        toolBar.translatesAutoresizingMaskIntoConstraints = false
        
        let views = ["toolBar" : toolBar , "cView" : conllecitonView] as [String : Any]
        let stringFormat = "H:|-0-[toolBar]-0-|"
        let stringFormat2 = "V:|-0-[cView]-0-[toolBar]-0-|"
        
        
        var cons = NSLayoutConstraint.constraints(withVisualFormat: stringFormat, options: [], metrics: nil, views: views)
        
        cons += NSLayoutConstraint.constraints(withVisualFormat:stringFormat2 , options: [.alignAllLeft,.alignAllRight], metrics: nil, views: views)
        view.addConstraints(cons)
        
        prepareForCollectionView()
        
        prepareForToolBar()
        
   
    }
    private func prepareForCollectionView() {
        conllecitonView.register(EmoticonCollectionViewCell.self, forCellWithReuseIdentifier:EmoticonCell)
        conllecitonView.dataSource = self
        conllecitonView.delegate = self
    }
    
    func prepareForToolBar() {
        let titles = ["最近" , "默认" , "emoji" , "浪小花"]
        
        var index = 0
        
        var tempItems = [UIBarButtonItem]()
        
        for title in titles{
            let item  = UIBarButtonItem(title: title, style: .plain, target: self, action: #selector(EmoticonViewController.itemClick(item:)))
            item.tag = index
            index = index + 1
            tempItems.append(item)
            //弹簧
         tempItems.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil))
            
        }
        tempItems.removeLast()
        toolBar.items = tempItems
        toolBar.tintColor = UIColor.orange
    }
    
    @objc private func itemClick(item :UIBarButtonItem){
//        print(item.tag)
        let tag = item.tag
        
        let indexPath = NSIndexPath(item: 0, section: tag)
        
        conllecitonView.scrollToItem(at: indexPath as IndexPath, at: .left, animated: true)
    
    }
}

//datasoures和delegate
extension EmoticonViewController : UICollectionViewDataSource , UICollectionViewDelegate{
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return manager.packages.count
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
//        return 200
        let package = manager.packages[section]
        print(package.emoticons.count)
        return package.emoticons.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: EmoticonCell, for: indexPath) as! EmoticonCollectionViewCell
        
//        cell.backgroundColor = indexPath.item % 2 == 0 ? UIColor.red : UIColor.blue
        
        
        let package = manager.packages[indexPath.section]
        let emoticon = package.emoticons[indexPath.item]
        
        cell.emotion = emoticon
        
        return cell
        
    }
    
    ///代理方法
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        let package = manager.packages[indexPath.section]
        
        let emotion = package.emoticons[indexPath.item]
        
        insertRecentlyEmoticon(emoticon: emotion)
        
        emoticonCallBack(emotion)
        
    }
    
    private func insertRecentlyEmoticon(emoticon : Emoticon){
        if emoticon.isEmpty || emoticon.isRemove {
            return
        }
        
        if manager.packages.first!.emoticons.contains(emoticon) {
            let index = manager.packages.first?.emoticons.index(of: emoticon)
            manager.packages.first?.emoticons.remove(at: index!)
            
        }else{
            manager.packages.first?.emoticons.remove(at: 19)
        }
        manager.packages.first?.emoticons.insert(emoticon, at: 0)
    }
    
}





